package com.hong.listener.impl;

import com.hong.Config.RpcServerConfig;
import com.hong.RpcServer;
import com.hong.listener.RpcServerListener;
import com.hong.qrpc.pojo.RegisterCenterConfig;
import com.hong.qrpc.register.Register;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author HQT
 * @Date 2022/10/29 13:41
 */
@Data
@NoArgsConstructor
public class NacosRegister implements RpcServerListener {
    private String helpDistinct = "com.hong.listener.impl.NacosRegister";
    private Register register;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        NacosRegister that = (NacosRegister) o;

        return getHelpDistinct().equals(that.getHelpDistinct());
    }

    @Override
    public int hashCode() {
        return getHelpDistinct().hashCode();
    }

    private List<RegisterCenterConfig> registerCenterConfigs = new ArrayList<>();

    public NacosRegister(Register register) {
        this.register = register;
    }

    //重写net启动之后的方法完成config里的port的更新
    @Override
    public void afterRpcServerStart(RpcServer rpcServer) {
        RpcServerConfig serverConfig = rpcServer.getConfigManager().getRpcServerConfig();
        serverConfig.setPort(rpcServer.getNet().getPort());
        for (RegisterCenterConfig registerCenterConfig : registerCenterConfigs) {
            registerCenterConfig.setServerPort(serverConfig.getPort());
            register.registerService(registerCenterConfig);
        }
    }

    public void addRegisterCenterConfig(RegisterCenterConfig registerCenterConfig) {
        registerCenterConfigs.add(registerCenterConfig);
    }

    public List<RegisterCenterConfig> getRegisterCenterConfigs() {
        return registerCenterConfigs;
    }

    public void setRegisterCenterConfigs(List<RegisterCenterConfig> registerCenterConfigs) {
        this.registerCenterConfigs = registerCenterConfigs;
    }
}
